package mysql

import (
	"log"
	"reflect"
	"strconv"
)

type DeviceCabinetStateMapper struct {
	ds *DataMysqlSourceClinet
}
type DeviceCabinetState struct {
	DeviceId   int64  `db:"device_id"`
	OnlineFlag string `db:"online_flag"`
}

func (dbm *DeviceCabinetStateMapper) QueryByDeviceId(deviceId int64) (*DeviceCabinetState) {
	sql := buildDeviceCabinetStateQuerySQL(strconv.FormatInt(deviceId, 10))
	return dbm.normalDeviceBaseInfoQuery(sql)
}

func (dbm *DeviceCabinetStateMapper) normalDeviceBaseInfoQuery(sql string) (*DeviceCabinetState) {
	var cabinetStates [] DeviceCabinetState
	e := dbm.ds.SqlDB.Select(&cabinetStates, sql)
	if e != nil {
		log.Println("查询失败！", e)
		return nil
	}
	if len(cabinetStates) == 0 {
		log.Println("设备不存在！")
		return nil
	}
	info := cabinetStates[0]
	return &info
}

func buildDeviceCabinetStateQuerySQL(vle string) string {
	var normalSql = "SELECT " + (&DeviceCabinetState{}).ToDbTagStr(false) + " FROM device_cabinet_state WHERE device_id = "
	return normalSql + vle
}
func (dbf *DeviceCabinetState) ToDbTagStr(Idexclude bool) string {
	of := reflect.ValueOf(dbf).Elem()
	var result = ""
	num := of.NumField()
	for i := 0; i < num; i++ {
		if Idexclude && i == 0 {
			continue
		}
		field := of.Type().Field(i)
		tag := field.Tag
		result = result + tag.Get("db") + ","
	}
	return result[0 : len(result)-1]
}
func NewDeviceCabinetStateMapper(ds *DataMysqlSourceClinet) (*DeviceCabinetStateMapper) {
	mapper := &DeviceCabinetStateMapper{}
	mapper.ds = ds
	return mapper
}
